﻿/**
 * Created in 2012-2-22.
 */
package kit4j.tests.jdk.runtime;

import java.io.File;

import kit4j.common.io.TxtExtractor;

/**
 * 
 * @author MiniKnife
 * 
 */
public class TestExec {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		testExecByProcessBuilder();
	}

	static void testExec() {
		String cmd = "dir >>test.txt 2>&1";
		cmd = "echo 1234555>D:\\1.txt";
		File runDir = new File("D:\\");

		try {
			Process process = Runtime.getRuntime().exec(cmd, null, runDir);

			System.out.println(TxtExtractor.getText(process.getErrorStream()));
			System.out.println(TxtExtractor.getText(process.getInputStream()));

			if (process.waitFor() != 0) {
				throw new RuntimeException("命令未成功执行[cmd=" + cmd + ",runDir="
						+ runDir.getAbsolutePath() + "]");
			}
		} catch (Exception e) {
			new RuntimeException(e);
		}

		System.out.println("run: " + cmd + "\nat :" + runDir.getAbsolutePath());
	}

	static void testExecByProcessBuilder() {
		String cmd = "javac";
		ProcessBuilder builder = new ProcessBuilder(cmd);
		
		try {
			Process process = builder.start();

			TxtExtractor.getText(process.getErrorStream());
			TxtExtractor.getText(process.getInputStream());

			if (process.waitFor() != 0) {
				throw new RuntimeException("命令未成功执行[cmd=" + cmd + ",runDir="
						+ builder.directory() + "]");
			}
		} catch (Exception e) {
			new RuntimeException(e);
		}

		System.out.println("run: " + cmd + "\nat :" + builder.directory());

		System.out.println(builder.environment());
	}

}
